import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import androidx.fragment.app.Fragment
import com.example.liaofengyun.R
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.nio.charset.StandardCharsets

class WordAddFragment : Fragment() {

    private lateinit var editTextWord: EditText
    private lateinit var buttonAddWord: Button

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.fragment_word_add, container, false)
        editTextWord = view.findViewById(R.id.editTextWord)
        buttonAddWord = view.findViewById(R.id.buttonAddWord)
        buttonAddWord.setOnClickListener {
            addWord()
        }
        return view
    }

    private fun addWord() {
        val word = editTextWord.text.toString()
        if (word.isNotEmpty()) {
            saveWordToFile(word)
            editTextWord.text.clear()
            // 可以根据需要添加提示信息或进行其他操作
        }
    }

    private fun saveWordToFile(word: String) {
        val file = File(requireContext().filesDir, "words.txt")
        try {
            val existingWords = if (file.exists()) {
                file.readLines(StandardCharsets.UTF_8).joinToString("\n")
            } else {
                ""
            }
            val newContent = if (existingWords.isNotEmpty()) "$existingWords\n$word" else word
            FileOutputStream(file).use { outputStream ->
                outputStream.write(newContent.toByteArray(StandardCharsets.UTF_8))
            }
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }
}